import md5 from 'js-md5'
import { cookie, toast, alert } from './wx-tools'
import store from '@/store'
import router from '@/router'
import { FIND_OPEN_SHOP_INFO, FIND_CUSTOMER_SHOP_OPEN_STATE } from '@/api'

export function formatNumber (n) {
  const str = n.toString()
  return str[1] ? str : `0${str}`
}

export function formatTime (date) {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  const t1 = [year, month, day].map(formatNumber).join('-')
  const t2 = [hour, minute, second].map(formatNumber).join(':')

  return `${t1} ${t2}`
}

export const encryptMD5 = str => md5(str).toUpperCase()

export const setToken = token => cookie.set('token', token)

export const getToken = () => cookie.get('token')

/**
 * 格式化数字
 *
 * @param {Number} number 数字
 * @param {Number} decimals 小数位数
 * @param {String} decPoint 小数点符号
 * @param {String} thousandsSep 千分位符号
 */
export const formatNumber2 = (
  number = 0,
  decimals = 2,
  decPoint = '.',
  thousandsSep = ','
) => {
  number = (number + '').replace(/[^0-9+-Ee.]/g, '')
  let toFixedFix = (n, prec) => {
    let k = Math.pow(10, prec)
    return (
      '' +
      parseFloat(
        Math.round(parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)
      ) /
        k
    )
  }
  let str = (decimals
    ? toFixedFix(number, decimals)
    : '' + Math.round(number)
  ).split('.')
  let reg = /(-?\d+)(\d{3})/
  while (reg.test(str[0])) {
    str[0] = str[0].replace(reg, '$1' + thousandsSep + '$2')
  }

  if ((str[1] || '').length < decimals) {
    str[1] = str[1] || ''
    str[1] += new Array(decimals - str[1].length + 1).join('0')
  }
  return str.join(decPoint)
}

export const openShopAction = customerId => {
  let params = {
    providerId: store.state.account.providerId,
    customerId
  }

  FIND_OPEN_SHOP_INFO(params)
    .then(r => {
      if (r.data.code === '0') {
        if (
          r.data.data &&
          (r.data.data.isFree === 'Y' || r.data.data.isPay === 'Y')
        ) {
          // 无需支付
          let { openShopOrderNo } = r.data.data

          FIND_CUSTOMER_SHOP_OPEN_STATE(params)
            .then(res => {
              if (res.data.code === '0') {
                if (res.data.data && res.data.data.state === -1) {
                  // 已经完成开店
                  alert('您的开店申请正在审核中')
                } else {
                  // 进入开店
                  router.push(
                    '/pages/open-shop/link/main?openShopOrderNo=' +
                      openShopOrderNo +
                      '&customerId=' +
                      customerId
                  )
                }
              } else {
                toast(res.data.message)
              }
            })
            .catch(err => {
              console.error(err)
            })
        } else {
          let { img, amount, openShopOrderNo } = r.data.data
          // 13270225546(测试账号)
          // 需要支付
          // router.push('/pages/open-shop/link/main')
          router.push(
            `/pages/open-shop/open-shop-set/main?img=${img}&amount=${amount}&openShopOrderNo=${openShopOrderNo}&customerId=${customerId}`
          )
        }
      } else {
        toast(r.data.message)
      }
    })
    .catch(e => {
      console.error(e)
    })
}

export const lastDayOfMonth = (year, month) => {
  let tempDate = new Date(`${year}/${month}/1`)

  tempDate.setMonth(month)
  tempDate.setDate(0)

  return tempDate.getDate()
}

export const numberArr = (start, end) => {
  let arr = []
  for (let index = 0; index <= end - start; index++) {
    arr[index] = start + index
  }
  return arr
}

/**
 * 判断一个对象是否为空对象
 *
 * @param {Object} obj
 */
export const isEmptyObject = obj => {
  for (let prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      return false
    }
  }
  return JSON.stringify(obj) === JSON.stringify({})
}

/**
 * 格式化时间
 *
 * @param {String} format 需要格式化的格式，如 yyyy-MM-dd hh:mm:ss
 * @param {Number, String, Date} date 时间
 */
export const dateFormatter = (format, date) => {
  if ((date !== 0 && !date) || isEmptyObject(date)) {
    return null
  }
  if (typeof date === 'string') {
    date = new Date(date.replace(/-/g, '/'))
  } else {
    date = new Date(date)
  }
  let o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds() // 毫秒
  }
  if (/(y+)/.test(format)) {
    format = format.replace(
      RegExp.$1,
      (date.getFullYear() + '').substr(4 - RegExp.$1.length)
    )
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
      )
    }
  }
  return format
}

export const validateIdCard = idCard => {
  const reg = /^\d{17}(\d|x|X)/

  if (!reg.test(idCard)) {
    return false
  }

  let verify = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
  let code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
  let sum = 0
  for (let i = 0; i < 17; i++) {
    sum += idCard[i] * verify[i]
  }
  let last = code[sum % 11]

  return idCard[17].toUpperCase() === last
}

/**
 * 获取两个时间月份差
 */
export const getMonths = (start, end) => {
  let result = []
  let starts = start.split('-')
  let ends = end.split('-')
  let staYear = starts[0] * 1
  let staMon = starts[1] * 1 < 10 ? starts[1] : starts[1]
  let endYear = ends[0] * 1
  let endMon = ends[1] * 1 < 10 ? ends[1] : ends[1]
  // result.push(staYear + '-' + staMon)
  result.push(Number(staMon))
  while (staYear <= endYear) {
    if (staYear === endYear) {
      while (staMon < endMon) {
        staMon++
        if (staMon < 10) {
          // result.push(staYear + '-0' + staMon)
          result.push(staMon)
        } else {
          // result.push(staYear + '-' + staMon)
          result.push(staMon)
        }
      }
      staYear++
    } else {
      staMon++
      if (staMon > 12) {
        staMon = 1
        staYear++
      }
      if (staMon < 10) {
        // result.push(staYear + '-0' + staMon)
        result.push(staMon)
      } else {
        // result.push(staYear + '-' + staMon)
        result.push(staMon)
      }
    }
  }
  // let indexOfArr = []
  // for (var i = 0; i < result.length; i++) {
  //   if (indexOfArr.indexOf(result[i]) === -1) {
  //     indexOfArr.push(result[i])
  //   }
  // }
  for (var i = 0; i < result.length; i++) {
    for (var j = i + 1; j < result.length; j++) {
      if (result[i] === result[j]) {
        // 第一个等同于第二个，splice方法删除第二个
        result.splice(i, 1)
        j--
      }
    }
  }
  return result
}
